package com.example.matchandroiddevices.test;

import android.app.Activity;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.matchandroiddevices.R;
import com.example.matchandroiddevices.test.util.RR7036ReaderUtil;
import com.hoho.android.usbserial.driver.UsbSerialDriver;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UsbSerialTerminalActivity extends Activity
        implements UsbDeviceDetector.UsbPermissionListener,
        UsbSerialCommunicator.SerialDataListener {

    private static final String TAG = "UsbSerialTerminal";

    // UI components
    private Button btnRefresh;
    private Button btnConnect;
    private Button btnSend;
    private Spinner spDevices;
    private Spinner spBaudRate;
    private EditText etCommand;
    private TextView tvResponse;
    private ListView lvDeviceList;

    // Controllers
    private UsbDeviceDetector usbDetector;
    private UsbSerialCommunicator serialComm;

    // Data
    private List<UsbDeviceDetector.DeviceInfo> deviceList = new ArrayList<>();
    private List<UsbSerialDriver> serialDrivers = new ArrayList<>();
    private UsbSerialDriver selectedDriver;
    private int selectedBaudRate = 9600;
    private StringBuilder receivedData = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_usb_serial_terminal);

        // 隐藏标题栏
        if (getActionBar() != null) {
            getActionBar().hide();
        }
        // Initialize UI components
        btnRefresh = findViewById(R.id.btnRefresh);
        btnConnect = findViewById(R.id.btnConnect);
        btnSend = findViewById(R.id.btnSend);
        spDevices = findViewById(R.id.spDevices);
        spBaudRate = findViewById(R.id.spBaudRate);
        etCommand = findViewById(R.id.etCommand);
        tvResponse = findViewById(R.id.tvResponse);
        lvDeviceList = findViewById(R.id.lvDeviceList);

        // Setup baud rate spinner
        ArrayAdapter<String> baudAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,
                new String[]{"19200", "38400", "57600", "115200", "230400", "460800", "921600"});
        baudAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spBaudRate.setAdapter(baudAdapter);
        spBaudRate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedBaudRate = Integer.parseInt(parent.getItemAtPosition(position).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedBaudRate = 9600;
            }
        });

        // Initialize controllers
        usbDetector = new UsbDeviceDetector(this, this);
        serialComm = new UsbSerialCommunicator(this, this);

        // Setup button listeners
        btnRefresh.setOnClickListener(v -> refreshDevices());

        btnConnect.setOnClickListener(v -> {
            if (selectedDriver != null) {
                // 请求权限并连接
                usbDetector.requestPermission(selectedDriver.getDevice());
            } else {
                Toast.makeText(this, "请先选择一个设备", Toast.LENGTH_SHORT).show();
            }
        });

        btnSend.setOnClickListener(v -> {
            byte[] command = etCommand.getText().toString().getBytes();
            if(command.length == 0){
                //读取读卡器
                command = RR7036ReaderUtil.createGetReaderInfoCommand((byte) 0x00);
                serialComm.sendData(command);
                //打开射频场
                command = RR7036ReaderUtil.createOpenRFCommand((byte) 0x00);
                serialComm.sendData(command);
                //切换至ISO15693
                command = RR7036ReaderUtil.createChangeToISO15693Command((byte) 0x00);
                serialComm.sendData(command);
//                //询查
//                command = RR7036ReaderUtil.createInventoryScanCommand((byte) 0x00,false);
//                serialComm.sendData(command);
            }else{
                String commandStr = etCommand.getText().toString();
                command = hexStringToByteArray(commandStr);
                byte[] crc = RR7036ReaderUtil.calculateCrc(command, command.length);
                // 创建完整命令（含CRC）
                byte[] fullCommand = new byte[6];
                System.arraycopy(command, 0, fullCommand, 0, command.length);
                fullCommand[4] = crc[0];  // LSB of CRC
                fullCommand[5] = crc[1];  // MSB of CRC
                // 发送命令
                serialComm.sendData(fullCommand);
            }
        });

        // Initial refresh
        refreshDevices();
    }
    public static byte[] hexStringToByteArray(String hexString) {
        // 移除所有的 "0x" 前缀和多余空格
        String cleanedString = hexString.replaceAll("0x", "").trim();

        // 按空格分割字符串
        String[] hexParts = cleanedString.split("\\s+");

        // 创建 byte 数组
        byte[] byteArray = new byte[hexParts.length];

        // 将每个十六进制字符串转换为 byte
        for (int i = 0; i < hexParts.length; i++) {
            byteArray[i] = (byte) Integer.parseInt(hexParts[i], 16);
        }

        return byteArray;
    }
    private void refreshDevices() {
        // 刷新USB设备列表
        usbDetector.refreshDeviceList();

        // 更新串口设备列表
        serialDrivers = serialComm.findUsbSerialDevices();

        if (serialDrivers.isEmpty()) {
            Toast.makeText(this, "未找到USB串口设备", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新设备下拉菜单
        List<String> deviceNames = new ArrayList<>();
        for (UsbSerialDriver driver : serialDrivers) {
            UsbDevice device = driver.getDevice();
            String name = String.format("%04X:%04X - %s",
                    device.getVendorId(), device.getProductId(),
                    device.getDeviceName());
            deviceNames.add(name);
        }

        ArrayAdapter<String> deviceAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, deviceNames);
        deviceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spDevices.setAdapter(deviceAdapter);

        spDevices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDriver = serialDrivers.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedDriver = null;
            }
        });

        // 默认选择第一个设备
        if (!serialDrivers.isEmpty()) {
            spDevices.setSelection(0);
            selectedDriver = serialDrivers.get(0);
        }
    }

    @Override
    public void onPermissionGranted(UsbDevice device) {
        Log.d(TAG, "Permission granted for device: " + device.getDeviceName());

        // 连接到串口设备
        if (selectedDriver != null && device.equals(selectedDriver.getDevice())) {
            boolean connected = serialComm.connect(selectedDriver, selectedBaudRate);
            if (connected) {
                Toast.makeText(this, "成功连接到串口设备", Toast.LENGTH_SHORT).show();
                // 启用发送按钮
                btnSend.setEnabled(true);
            } else {
                Toast.makeText(this, "连接串口设备失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPermissionDenied(UsbDevice device) {
        Log.d(TAG, "Permission denied for device: " + device.getDeviceName());
        Toast.makeText(this, "USB权限被拒绝", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDevicesDetected(List<UsbDeviceDetector.DeviceInfo> devices) {
        this.deviceList = devices;

        // 更新设备详情列表
        List<String> deviceDetails = new ArrayList<>();
        for (UsbDeviceDetector.DeviceInfo info : devices) {
            deviceDetails.add(info.toString());
        }

        ArrayAdapter<String> detailsAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, deviceDetails);
        lvDeviceList.setAdapter(detailsAdapter);
    }

    @Override
    public void onDataReceived(byte[] data) {
        // 处理接收到的数据
        final var received = RR7036ReaderUtil.parseReaderInfoSimple(data);
        Log.d(TAG,"received: " + Arrays.toString(data));
        // 更新UI (需要在主线程)
        runOnUiThread(() -> {
            receivedData.append(received);
            receivedData.append("\r\n\r\n");
            // 限制显示的数据量
            if (receivedData.length() > 5000) {
                receivedData.delete(0, receivedData.length() - 4000);
            }
            tvResponse.setText(receivedData.toString());
        });
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "Serial communication error", e);

        runOnUiThread(() -> {
            Toast.makeText(this, "通信错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            // 断开连接并禁用发送按钮
            serialComm.disconnect();
            btnSend.setEnabled(false);
        });
    }

    @Override
    protected void onDestroy() {
        // 断开连接
        if (serialComm != null) {
            serialComm.disconnect();
        }

        // 释放 USB 检测器资源
        if (usbDetector != null) {
            usbDetector.release();
        }

        super.onDestroy();
    }
}
